<?php

namespace app\index\controller;

use app\admin\model\Service;
use app\index\model\User;

class Serve extends Base
{
    /**
     * @return mixed
     */
    public function index()
    {
        $openid = $this->wechat_user['openid'];
        /**
         * @var User
         */
        $user = User::where('openid', $openid)->find();
        $service = Service::where('openid', $openid)->find();
        if ($service) {
            $this->servicePage($service);
        } elseif (!$user) {
            return $this->redirect('index/register/index');
        } elseif (1 != $user['status']) {
            return $this->redirect('index/register/ok');
        } else {
            $this->userPage($user);
        }

        return $this->fetch();
    }

    /**
     * @param Service $role
     * @return mixed
     */
    public function servicePage(Service $role)
    {
        $service = null;
        $users = collect();
        switch ($role->role) {
            case Service::ROLE_DEPARTMENT:
                $service = $role->superior;
                $users = User::where('department_id', $role->id)->select();
                break;
            case Service::ROLE_SHOP:
                $users = User::where('shop_id', $role->id)->select();
                $m = $role->superior()->find();
                if ($m) {
                    $d = $m->superior()->find();
                    if ($d) {
                        $service = $d->superior()->find();
                    }
                }
                break;
            case Service::ROLE_MARKET:
                $users = User::where('market_id', $role->id)->select();
                $d = $role->superior()->find();
                if ($d) {
                    $service = $d->superior()->find();
                }
                break;
            default:
                break;
        }

        $this->assign([
            'service' => optional($service),
            'users' => $users
        ]);
        return $this->fetch();
    }

    /**
     * @param User $user
     * @return mixed
     */
    public function userPage(User $user)
    {
        $this->assign([
            'service' => optional($user->service),
            'users' => collect()
        ]);
        return $this->fetch();
    }
}
